package zwxsrv

import (
	"log"
	"sync"
	"time"

	"gitee.com/zevenfly/goutil/zweixin"
)

// 管理 access_token 更新
type AccessTokenMan struct {
	accessToken string
	expiresTime time.Time

	appId     string
	appSecret string

	mutex sync.RWMutex
}

// 创建 access_token 管理对象
func NewAccessTokenMan(appId, appSecret string) *AccessTokenMan {
	return &AccessTokenMan{
		appId:     appId,
		appSecret: appSecret,
	}
}

// 设置 access_token
func (atm *AccessTokenMan) set(accessToken string, expiresTime time.Time) {
	atm.mutex.Lock()
	defer atm.mutex.Unlock()

	atm.accessToken = accessToken
	atm.expiresTime = expiresTime
}

// 获取 access_token
func (atm *AccessTokenMan) Get() string {
	atm.mutex.Lock()
	defer atm.mutex.Unlock()

	return atm.accessToken
}

// 获取 access_token
func (atm *AccessTokenMan) GetEx() (string, time.Time) {
	atm.mutex.Lock()
	defer atm.mutex.Unlock()

	return atm.accessToken, atm.expiresTime
}

// 启动更新 access_token 服务
func (atm *AccessTokenMan) Run() {
	for {
		// todo: 检测设备的时间和公网时间偏差

		accessToken, expiresIn, errmsg := zweixin.ApiUpdateAccessToken(atm.appId, atm.appSecret)
		if accessToken == "" {
			log.Println("update access_token error:", errmsg)
			time.Sleep(time.Second * 60 * 5)
			continue
		}

		expiresIn -= 60 * 5
		atm.set(accessToken, time.Now().Add(time.Second*time.Duration(expiresIn)))

		time.Sleep(time.Second * time.Duration(expiresIn))
	}
}
